import java.io.*;
import java.util.ArrayList;

public class FileDeal {
    private File infile;
    private String unionlines;
    private boolean inFormatString;
    private boolean inComment;

    public FileDeal(File infile) {
        this.infile = infile;
        this.unionlines = "";
        this.inFormatString = false;
        this.inComment = false;
    }

    //读文件
    public void readFile() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(infile));

        String line;
        while ((line = br.readLine()) != null) {
            line = delcomment(line);
            line += '\n';
            unionlines += line;
        }
    }

    public String getUnionlines() {
        return unionlines;
    }

    //拼接子串
    public String splicing(String line, int begin, int end) {
        String left  = line.substring(0, begin);
        String right = line.substring(end + 1, line.length());
        line = left + " " + right;
        return line;
    }

    //去除注释
    public String delcomment(String line) {
        int commentbegin = 0;
        int commentend = line.length();
        for (int i = 0; i < line.length(); i++) {
            if (line.charAt(i) == '/' && i != line.length() - 1 && line.charAt(i + 1) == '/') {
                if (!inComment && !inFormatString) {
                    if (i == 0) {
                        line = "";
                    } else {
                        line = line.substring(0, i);
                    }
                    break;
                }
            } else if (line.charAt(i) == '/' && i != line.length() - 1 && line.charAt(i + 1) == '*') {
                if (!inComment && !inFormatString) {
                    inComment = true;
                    commentbegin = i;
                    i++;
                }
            } else if (line.charAt(i) == '*' && i != line.length() - 1 && line.charAt(i + 1) == '/') {
                if (inComment && !inFormatString) {
                    inComment = false;
                    commentend = i + 1;
                    line = splicing(line, commentbegin, commentend);
                    i = commentbegin;
                }
            } else if (line.charAt(i) == '"') {
                if (!inComment && !inFormatString) {
                    inFormatString = true;
                } else if (!inComment && inFormatString) {
                    inFormatString = false;
                }
            }
        }
        if (inComment) {
            line = line.substring(0, commentbegin);
        }
        return line;
    }
}
